﻿@using MyDocuments.Shared;
@inject Task<HttpClient> tHttp
@inject IJSRuntime js

<Spin Spinning=loading>
    @if (files == null)
    {
        <p><em>Loading...</em></p>
    }
    else
    {
        <Search 
            Placeholder="input search text" 
            @bind-Value="searchValue" 
            OnSearch="() => OnSearch()" 
            OnChange="() => OnSearchChange()"
            WrapperStyle=" border:1px solid #797979;width: 238px; margin: 0 0 10px 20px; background: none;" 
            ClassicSearchIcon
            AllowClear />

        <Menu 
            Theme="MenuTheme.Dark" 
            Mode="MenuMode.Inline"
            Accordion="true" 
            Multiple="false">
            @foreach (var item in files)
            {
                @GetMenuEles(item)
                ;
            }
        </Menu>
    }
</Spin>

@code {
    private FileNames[ ] files;
    private FileNames[ ] allFiles;
    public bool loading { get; set; } = true;
    private string searchValue;

    [Parameter]
    public EventCallback<FileSave> OnClickFileChanged { get; set; }

    protected override async Task OnInitializedAsync()
    {

        var value = await js.InvokeAsync<string?>("localStorage.getItem", "token");
        if (string.IsNullOrWhiteSpace(value))
        {
            navigationManager.NavigateTo("/Login");
        }

        await CheckToken();

        try
        {
            await js.InvokeVoidAsync("shortcuts.add", "Ctrl+s", typeof(JSLibrary).Namespace, nameof(JSLibrary.SaveEvent));
            await js.InvokeVoidAsync("shortcuts.add", "F2", typeof(JSLibrary).Namespace, nameof(JSLibrary.F2Event));
            await js.InvokeVoidAsync("shortcuts.add", "F1", typeof(JSLibrary).Namespace, nameof(JSLibrary.NEvent));
            await js.InvokeVoidAsync("shortcuts.add", "Ctrl+n", typeof(JSLibrary).Namespace, nameof(JSLibrary.NEvent));
            await js.InvokeVoidAsync("shortcuts.add", "F5", typeof(JSLibrary).Namespace, nameof(JSLibrary.F5Event));
            await js.InvokeVoidAsync("shortcuts.add", "Ctrl+Insert", typeof(JSLibrary).Namespace, nameof(JSLibrary.NEvent));
            await js.InvokeVoidAsync("shortcuts.add", "Ctrl+Delete", typeof(JSLibrary).Namespace, nameof(JSLibrary.DelEvent));
            await js.InvokeVoidAsync("shortcuts.add", "Ctrl+p", typeof(JSLibrary).Namespace, nameof(JSLibrary.PriviewEvent));
            //await js.InvokeVoidAsync("shortcuts.add", "Ctrl+f", typeof(JSLibrary).Namespace, nameof(JSLibrary.SearchEvent));
            await js.InvokeVoidAsync("shortcuts.add", "Ctrl+h", typeof(JSLibrary).Namespace, nameof(JSLibrary.ShareEvent));
            await js.InvokeVoidAsync("shortcuts.start", null);
            await LoadFiles();
            if (JSLibrary.IsSaveEventNull(nameof(JSLibrary.Ctrl_F5_Event)))
            {
                JSLibrary.Ctrl_F5_Event += (s, e) => LoadFiles();
                //JSLibrary.Ctrl_F_Event += (s, e) => Search();
            }
        }
        catch (Exception exception)
        {
            var xxx = exception.Message;
            Console.WriteLine(xxx);
        }
    }

    private async void ClearSearch()
    {
        this.searchValue = "";
        await LoadFiles();
        StateHasChanged();
    }

    private async void OnSearch()
    {
        await LoadFiles();
    }

    private void OnSearchChange()
    {
        if ( string.IsNullOrWhiteSpace(searchValue) && allFiles?.Any() == true )
        {
            files = allFiles;
        }
    }

    private async Task LoadFiles()
    {
        this.loading = true;
        base.StateHasChanged();
        await Task.Delay(100);
        var Http = await tHttp;
        if (string.IsNullOrWhiteSpace(searchValue))
        {
            allFiles = files = await Http.GetFromJsonAsync<FileNames[ ]>("File") ?? new FileNames[ 0 ];
        }
        else
        {
            files = await Http.GetFromJsonAsync<FileNames[]>("File/s/" + searchValue) ?? new FileNames[0];
        }

        this.loading = false;
        base.StateHasChanged();
    }

    async Task CheckToken()
    {
        var Http = await tHttp;
        var result = await Http.GetStringAsync("/token");

        if (result != "ok")
        {
            if (result == "ini")
            {
                navigationManager.NavigateTo("/Config");
            }
            else
            {
                navigationManager.NavigateTo("/Login");
            }
        }
    }

    private RenderFragment GetEle(string name, FileNames item)
    {
        return
    @<span style=" width:100%;display: block; " @onclick="()=>onselectMenu(item)">
        <span>@name</span>
        </span>
    ;
    }

    private RenderFragment GetMenuEles(FileNames item, bool isFirst = true)
    {
        if (item.Children?.Any() == true || item.isDirectory)
        {
            if (isFirst)
            {
                //rootSubmenuKeys.Add(item.Id);
            }

            return
    @<SubMenu Key="@item.Id" TitleTemplate=GetEle(item.Name,item)>
        @foreach (var ccc in (item.Children ?? new List<FileNames>()))
        {
            @GetMenuEles(ccc,false);
        }
    </SubMenu>;
        }
        else
        {
            return
    @<MenuItem Key="@item.Path" @onclick="() => OnClickFile(item)">
        <span>@item.Name</span>
        </MenuItem>
    ;
        };
    }

    async void onselectMenu(FileNames item)
    {
        await OnClickFileChanged.InvokeAsync(new FileSave
        {
            Type = FileSaveEnum.CreateFolder,
            Value = item.Path,
            PWD = item.Pwd
        });
    }

    async void OnClickFile(FileNames item)
    {
        if (OnClickFileChanged.HasDelegate)
        {
            await OnClickFileChanged.InvokeAsync(new FileSave

                {
                    Type = FileSaveEnum.Create,
                    Value = item.Path,
                    PWD = item.Pwd
                });
        }
    }

}


<style>
    aside.ant-layout-sider {
        flex: 0 0 288px !important;
        max-width: 288px !important;
        min-width: 288px !important;
        width: 288px !important;
        max-height: 100% !important;
        overflow-x: auto !important;
    }


    .ant-input-search input {
        background: rgba(0,0,0,0) !important;
        color: white !important;
    }

    .ant-input-search .ant-input-suffix {
        color: white !important;
    }

    .ant-input-search .ant-input-clear-icon {
        color: rgba(255, 255, 255, 0.5) !important;
    }
    </style>